package com.stu.manager.studentscoremanagersys.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.stu.manager.studentscoremanagersys.Utils.ResponseUtils;
import com.stu.manager.studentscoremanagersys.consts.constants;
import com.stu.manager.studentscoremanagersys.context.ContextManager;
import com.stu.manager.studentscoremanagersys.dto.JWTManagerDTO;
import com.stu.manager.studentscoremanagersys.Utils.JWTUtil;
import com.stu.manager.studentscoremanagersys.enums.CodeEnum;
import com.stu.manager.studentscoremanagersys.res.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthorationInterCeptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过来的请求/student/list
        log.info("过来的请求{}",request.getServletPath());
        //axios对非简单请求有时候会通过options来匹配请求方法是否支持跨域
        String method = request.getMethod();
        if (HttpMethod.OPTIONS.matches(method)){
            //匹配就放过，执行下一步
            return true;
        }
        //获取token
        String tokenVertity= request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(tokenVertity)){
            tokenVertity = request.getParameter(constants.USER_TOKEN_KEY);
            if (StringUtils.isBlank(tokenVertity)){
                ResponseUtils.ResponseJson(response,Result.buildFailure(CodeEnum.AUTH_ERROR));
                return false;
            }
        }
        //验证token
        Result<DecodedJWT> valiResult = JWTUtil.vali(tokenVertity);
        if (valiResult.isFailure()){
            ResponseUtils.ResponseJson(response,Result.buildFailure(CodeEnum.AUTH_ERROR));
            return false;
        }
        //解析token
        JWTManagerDTO jwtManagerDTO  =  JWTUtil.parse(valiResult.getData(),JWTManagerDTO.class);
        if (jwtManagerDTO== null){
            ResponseUtils.ResponseJson(response,Result.buildFailure(CodeEnum.AUTH_ERROR));
            return false;
        }
        //解析出来在请求的县城中随处可用，(在任意的层，controller，service等层可以使用)
        //threadLocal
        ContextManager.set(jwtManagerDTO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ContextManager.remove();
    }
}
